<template>
  <div style="margin-top: '20px'">
    <el-form
      :rules="rules"
      :model="spuForm"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input
          v-model="spuForm.spuName"
          placeholder="请输入SPU名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌" prop="tmId">
        <el-select v-model="spuForm.tmId" placeholder="请输入SPU品牌">
          <el-option
            v-for="trademark in trademarkList"
            :key="trademark.id"
            :label="trademark.tmName"
            :value="trademark.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input type="textarea" v-model="spuForm.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          class="avatar-uploader"
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuForm.spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select v-model="spuSaleAttrStr" placeholder="请选择销售属性">
          <el-option
            v-for="spuSale in filterBaseSaleAttrList"
            :key="spuSale.id"
            :label="spuSale.name"
            :value="`${spuSale.id}:${spuSale.name}`"
          ></el-option>
        </el-select>
        <template>
          <el-button
            type="primary"
            icon="el-icon-plus"
            style="margin-left: 20px"
            :disabled="!spuSaleAttrStr"
            @click="addSaleAttr"
          >
            添加销售属性
          </el-button>
          <el-table
            :data="spuForm.spuSaleAttrList"
            border
            style="width: 100%; margin: 20px 0"
          >
            <el-table-column
              label="序号"
              type="index"
              width="80"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="saleAttrName"
              label="属性名"
              width="150"
              align="center"
            >
            </el-table-column>
            <el-table-column label="属性值列表">
              <template slot-scope="{ row, $index }">
                <el-tag
                  closable
                  style="margin-right: 5px"
                  v-for="(spuValueItem, index) in row.spuSaleAttrValueList"
                  :key="spuValueItem.uId"
                  @close="row.spuSaleAttrValueList.splice(index, 1)"
                >
                  {{ spuValueItem.saleAttrValueName }}
                </el-tag>
                <el-input
                  v-if="row.isShowEdit"
                  v-model="saleAttrValue"
                  placeholder="请输入属性值"
                  ref="valueRef"
                  @blur="handleInputConfirm(row)"
                ></el-input>
                <el-button
                  icon="el-icon-plus"
                  size="small"
                  style="margin-left: 20px"
                  v-else
                  @click="addSaleValue(row)"
                >
                  添加属性值
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template slot-scope="{ row, $index }">
                <el-popconfirm
                  title="确定删除吗？"
                  @onConfirm="removeSpuValue($index)"
                >
                  <el-button
                    icon="el-icon-delete"
                    style="color: red"
                    slot="reference"
                  >
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-form-item>
    </el-form>

    <el-button type="primary" size="min" style="margin-top: 20px" @click="save">
      确认
    </el-button>
    <el-button size="min" style="margin-top: 20px" @click="cancel">
      取消
    </el-button>
  </div>
</template>

<script>
import {
  getSpuTrademarkListApi,
  getSaleAttrListApi,
  getAddSpuApi,
  getUpdateSpuApi,
  spuSaleAttrListApi,
  spuImgListApi,
} from "@/api/product/spu/spu";
export default {
  name: "AddOrUpdateSpu",
  props: {
    category3Id: Number,
    setSpuList: Object,
  },
  data() {
    const { spuName, description, tmId, spuImageList, spuSaleAttrList, id } =
      this.setSpuList;
    return {
      spuForm: {
        spuName: spuName || "",
        description: description || "",
        tmId: tmId || undefined,
        spuImageList: spuImageList || [],
        spuSaleAttrList: spuSaleAttrList || [],
        id: id || undefined,
      },
      dialogVisible: false,
      spuSaleAttrList: [],
      trademarkList: [],
      spuImageList: [],
      dialogImageUrl: "",
      spuSaleAttrStr: "",
      saleAttrValue: "",
      rules: {
        spuName: [
          { required: true, message: "请输入SPU名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "change",
          },
        ],
        tmId: [{ required: true, message: "请选择SPU品牌", trigger: "change" }],
        description: [
          { required: true, message: "请填写SPU描述", trigger: "blur" },
        ],
        spuImageList: [{ required: true, message: "请选择至少上传一张图片" }],
        spuSaleAttrList: [
          { required: true, message: "至少添加一个销售属性", trigger: "blur" },
        ],
      },
      isShow: true,
    };
  },
  async mounted() {
    const res = await getSpuTrademarkListApi();
    const res1 = await getSaleAttrListApi();
    this.trademarkList = res.data;
    this.spuSaleAttrList = res1.data;
    if (!this.spuForm.id) return;
    const res2 = await spuSaleAttrListApi(this.spuForm.id);
    this.spuForm.spuSaleAttrList = res2.data;
    const res3 = await spuImgListApi(this.spuForm.id);
    res3.data.forEach((item) => {
      item.name = item.imgName;
      item.url = item.imgUrl;
    });
    this.spuForm.spuImageList = res3.data;
  },
  methods: {
    cancel() {
      this.$emit("showPage",1);
    },
    //删除属性
    removeSpuValue(index) {
      this.spuForm.spuSaleAttrList.splice(index, 1);
    },
    //编辑模式切换
    addSaleValue(row) {
      if (!this.isShow) return;
      this.$set(row, "isShowEdit", true);
      this.$nextTick(() => {
        this.$refs.valueRef.focus();
      });
    },
    //失去焦点
    handleInputConfirm(row) {
      if (!this.saleAttrValue) {
        this.$message.info("值不能为空");
        this.isShow = false;
        row.isShowEdit = false;
        this.isShow = true;
        return;
      } else {
        this.isShow = true;
        row.isShowEdit = false;
        row.spuSaleAttrValueList.push({
          uid: Date.now(),
          saleAttrValueName: this.saleAttrValue,
          baseSaleAttrId: row.baseSaleAttrId,
        });
        this.saleAttrValue = "";
      }
    },
    //添加销售属性
    addSaleAttr() {
      const [id, name] = this.spuSaleAttrStr.split(":");
      let AttrList = {
        baseSaleAttrId: +id,
        saleAttrName: name,
        spuSaleAttrValueList: [],
      };
      this.$set(AttrList, "isShowEdit", false);
      this.spuForm.spuSaleAttrList.push(AttrList);
      // {
      // baseSaleAttrId: id,
      // saleAttrName: name,
      // {
      //   baseSaleAttrId: 0,
      //   id: 0,
      //   isChecked: 'string',
      //   saleAttrName: 'string',
      //   saleAttrValueName: 'string',
      //   spuId: 0,
      // },
      // }
      // );
      this.spuSaleAttrStr = "";
    },
    //添加
    save() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const {
            description,
            spuImageList,
            spuName,
            spuSaleAttrList,
            tmId,
            id,
          } = this.spuForm;
          const category3Id = this.category3Id;
          const data = {
            description,
            spuImageList:spuImageList.map((img)=>{
              return{
                imgUrl:img.response.data,
                imgName:img.response.name
              }
            }),
            spuName,
            spuSaleAttrList,
            tmId,
            id,
            category3Id,
          };

          if (id) {
            await getUpdateSpuApi(data);
          } else {
            await getAddSpuApi(data);
          }
          this.$message.info(`${id ? "更新" : "添加"}成功`);
          this.cancel();
        } else {
          this.$message.info(`${id ? "更新" : "添加"}成功`);
          return false;
        }
      });
    },
    //删除图片时的钩子
    handleRemove(file, fileList) {
      console.log("删除图片时的钩子", file, fileList);
      this.spuForm.spuImageList = fileList;
    },
    //点击图片放大时钩子
    handlePictureCardPreview(file) {
      console.log("点击图片放大时钩子", file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //上传成功时的钩子
    handleAvatarSuccess(res, file, fileList) {
      // console.log('上传成功时的钩子',res, file,fileList)
      this.spuForm.spuImageList = fileList;
    },
  },
  computed: {
    filterBaseSaleAttrList() {
      return this.spuSaleAttrList.filter((supList) => {
        return !this.spuForm.spuSaleAttrList.find(
          (spuSaleAttr) => spuSaleAttr.baseSaleAttrId === supList.id
        );
      });
    },
  },
};
</script>

<style></style>
